<template>
  <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>重置密码</span>
  </div>
  <!-- 内容取 -->
  <el-form label-width="100px" ref="form" :model="pass" :rules="rules">
    <el-form-item label="原密码:" prop="old_pwd">
      <el-input v-model="pass.old_pwd" type="password" show-password placeholder="请输入原密码"></el-input>
    </el-form-item>
    <el-form-item label="新密码:" prop="new_pwd">
      <el-input v-model="pass.new_pwd" type="password" show-password placeholder="请输入新密码"></el-input>
    </el-form-item>
    <el-form-item label="确认新密码:" prop="new_pwd">
      <el-input v-model="pass.re_pwd" type="password" show-password placeholder="请确认新密码"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updatePwd">确认修改</el-button>
      <el-button>不改了</el-button>
    </el-form-item>
  </el-form>
</el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/user'
export default {
  data() {
    const newPwd = (rule, value, callback) => {
      // value 表示输入框的值
      // callback() 表示通过    callback(new Error('请再次输入密码'))表示不通过
      if (value === this.pass.old_pwd) {
        callback(new Error('密码不能和原密码一样'))
      } else {
        callback()
      }
    }
    const rePwd = (rule, value, callback) => {
      if (value === this.pass.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      // 数据项
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
          { validator: newPwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('验证通过，提交数据')
        const { data: res } = await updatePwdAPI(this.pass)
        if (res.code === 0) {
          this.$message.success(res.message)
          // 更新成功，更新vuex中的 user 数据
          // this.$refs.form.resetFields()
          this.$store.commit('user/updateToken', '')
          this.$store.commit('user/updateUser', {})
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" copend>
  .el-card{
    // width: 500px;
    font-size: 14px;
    font-weight: 700;
  }
  .el-form{
    width: 500px;
  }
</style>
